import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import urllib
from google.appengine.api import urlfetch

import sys
import httplib
import re
import string

import datastore
import library
from datetime import date

class USTATeam(db.Model):

 def Write(self,t):
    self.response.out.write(t)

 def GetTeams(self,url, league, year,start,finish):
    print(" ")
    teams=library.GetTeams( url)

    tlist= []
    for i,t in teams:
        teamid= t[0]
        g = datastore.USTATeam( key_name= teamid )
        g.idx    = str(i)
        g.teamid = t[0]
        g.name   = t[1]
        g.league   = league
        g.level    = league
        g.year     = year

        print("go")
        print("i=",i," start=",start)
#        print( "<br>")

        if( int(i)<start  ): continue
        if( int(i)>finish ): break

        tlist.append( g )
        print( g.idx ,   g.teamid ,  year , league , g.name )
        if(library.LocalHost()!= True ): print( "<br>")
        library.LocalHost()

    db.put( tlist )

 def show(self):
    query="select __key__ from League order by idx"
    keys  = db.GqlQuery( query )
    for k in keys:
     t = db.get(k)
     print t
     print t.name


# ------------------------


class MainPage(webapp.RequestHandler):

  def Write(self,t):
    self.response.out.write(t)

  def get(self):

    league =  self.request.get('league') 
    start =  self.request.get('start') 
    finish =  self.request.get('finish') 
    if(start=="" or finish==""):  
       start=0
       finish=5



    if( league == "M5.0"):
      url  = "http://www.ustanorcal.com/standings.asp?a=&l=5928:889&r=L"  #2011 M5.0
    elif( league == "M4.5"):
      url = " http://www.ustanorcal.com/standings.asp?a=&l=5868:888&r=L"
    elif( league == "M4.0"):
      url = "http://www.ustanorcal.com/standings.asp?a=&l=5824:887&r=L"
    elif( league == "W4.5"):
      url = "http://www.ustanorcal.com/standings.asp?a=&l=5910:896&r=L"  
    elif( league == "W4.0"):
      url = "http://www.ustanorcal.com/listteams.asp?leagueid=895"
    elif( league == "W3.5"):
      url = "http://www.ustanorcal.com/standings.asp?a=&l=5806:894&r=L"
    else:
      url = "http://www.ustanorcal.com/standings.asp?a=&l=5824:887&r=L"
      league = "M4.0"


    year     = "2011"

    team = USTATeam()
    team.GetTeams( url, league, year, int(start), int(finish)  )
     

application = webapp.WSGIApplication(
                                     [('/ustateams', MainPage)],
                                     debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":

#   print __file__
#   print __name__

    main()
